package com.facebook.android;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class Notifications extends Activity {
	
	private Facebook facebook;
	private Button back;
	private ListView list;
	private ArrayAdapter<String> adapter;
	// uid -> name
	private static Map<String, String> friends;
	// name -> uid
	private static Map<String, String> reversedMap;
	// uid challenger -> questions
	private static Map<String, String> challengers;
	private static String myID;
	
	public void onCreate(Bundle savedInstanceState) {
	     super.onCreate(savedInstanceState);
	     
	     // Getting the Bundle with the information from the Intent
	     Bundle stuff = this.getIntent().getExtras();
	     // Getting the APP_ID
	     final String app_id = stuff.getString("api");
	     String text = stuff.getString("friends");
	     myID = stuff.getString("myID");
	     facebook = new Facebook(app_id);
	     // Restoring the session by obtaining the session key
	     SessionStore.restore(facebook, this);  
	     
	     // Instantiate the data structures
	     instantiateData(text);
	     setTitle("You have been challenged by:");

	     
	     if(friends.size() == 0){
	    	 TextView tv = new TextView(this);
	    	 tv.setText("None of your friends uses PennQuiz. Invite them!");
	    	 setContentView(tv);
	     }
	     
	     else {
		     // Set challenge layout
		     setContentView(R.layout.notifications);
		     // Get id of the challenge button
		     back = (Button) findViewById(R.id.notif_back);
		     
		     // Get the people who challenged you
		     Collection<String> coll = challengers.keySet();
		     final String[] array = new String[coll.size()];
		     int i = 0;
		     for(Iterator<String> it = coll.iterator(); it.hasNext(); ){
		    	 String next = it.next();
		    	 array[i] = friends.get(next);
		    	 i++;
		     }
		     Arrays.sort(array);
		     
		     // Create an adapter with the string
		     adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, array);
		     list = (ListView) findViewById(R.id.list);
		     list.setAdapter(adapter);
		     // the items in the list won't contain focusable inner content
		     list.setItemsCanFocus(false);
		     // Enables search by typing
		     list.setTextFilterEnabled(true);
		     list.setClickable(true);
		     
		     // Add a listener for the multiple choice list
		     list.setOnItemClickListener(new OnItemClickListener(){
				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					
					String selectedFromList = list.getItemAtPosition(arg2).toString();
					final String uid = reversedMap.get(selectedFromList);
					
					// arg0.getContext() returns the context where the alert dialog goes into
					AlertDialog.Builder builder = new AlertDialog.Builder(arg0.getContext());
					builder.setMessage("Would you like to take the challenge from " 
							+ selectedFromList + "?")
					       
					       // Positive
					       .setPositiveButton("Accept", new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog, int id) {
								dialog.cancel();
								
								// Begin the loading dialog
								final ProgressDialog progress = ProgressDialog.show(
										Notifications.this, "", "Loading...", true);
								
								// get questions
								String[] questions = challengers.get(uid).split(",");
					            
							    final Intent intent = new Intent(findViewById(R.id.main_notif_view).getContext(), SinglePlay.class);
					            // I am sending the APP_ID and the friends 
							    // on the other side to connect both
							    // and the userID
					            intent.putExtra("api", app_id);
					            intent.putExtra("questions", questions);
					            intent.putExtra("myID", myID);
					            intent.putExtra("score", 0);
					            
					            // launch the accept function
					            // it changes the state of the `done` field
				                String domain = "http://www.pennquiz.com/users.php";
				    			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
				    			nameValuePairs.add(new BasicNameValuePair("user", uid));
				    			nameValuePairs.add(new BasicNameValuePair("uid", myID));
				    			nameValuePairs.add(new BasicNameValuePair("funct","accept"));
				    			RequestPoster rp = new RequestPoster(domain, nameValuePairs);
				    			rp.execute();            
					            
					            // Put the dialog in a new thread so that it can close 
					            // properly afterwards
					            new Thread(new Runnable(){
					            	public void run(){
					            		startActivity(intent);
					            		progress.dismiss();
					            		finish();
					            	}
					            	}).start();
					            //startActivity(intent);
							}
					       })
					       
					       // Neutral
					       .setNeutralButton("Close", new DialogInterface.OnClickListener() {
							
							@Override
							public void onClick(DialogInterface dialog, int which) {
								dialog.cancel();
							}
					       })
					       
					       // Decline
					       .setNegativeButton("Decline", new DialogInterface.OnClickListener() {
					           public void onClick(DialogInterface dialog, int id) {
					        	   	// cancel the dialog
					                dialog.cancel();
					                
					                // launch the decline function
					                String domain = "http://www.pennquiz.com/users.php";
					    			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
					    			nameValuePairs.add(new BasicNameValuePair("user", uid));
					    			nameValuePairs.add(new BasicNameValuePair("uid", myID));
					    			nameValuePairs.add(new BasicNameValuePair("funct","decline"));
					    			RequestPoster rp = new RequestPoster(domain, nameValuePairs);
					    			rp.execute();
					    			
					    			// restart the activity
					    			final Intent intent = getIntent();
					    			finish();
					    			startActivity(intent);
					           }
					       });
					
					// create the alert with all the properties
					// and show it on the screen
					AlertDialog alert = builder.create();
					alert.show();
				} 
		     });
		     
		     // On done, just go back
		     back.setOnClickListener(new OnClickListener(){
					@Override
					public void onClick(View v) {
						finish();
					} 
			     });
	     }
	}
    
	/* getFriends return the user's friends from Facebook
	 * sorted by name. The function takes parameter result
	 * which is a JSONArray of all JSONObjects that
	 * represent pairs of names and IDs of the people.
	 */
    private static void instantiateData(String result){
    	// Load the requested page converted to a string into a JSONObject.  
		JSONObject json;
		try {
			json = new JSONObject(result);
			
			// Make array of the suggestions  
			JSONArray suggestions = json.getJSONArray("data");
			friends = new TreeMap<String, String>();
			reversedMap = new TreeMap<String, String>();
			challengers = new TreeMap<String, String>();
	
			// Build the friends map.
			for(int i = 0; i < suggestions.length(); i++){
				JSONObject single = suggestions.getJSONObject(i);
				friends.put(single.getString("id"), single.getString("name"));
				reversedMap.put(single.getString("name"), single.getString("id"));
			}
			
			String domain = "http://www.pennquiz.com/users.php";
			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			nameValuePairs.add(new BasicNameValuePair("user", myID));
			nameValuePairs.add(new BasicNameValuePair("funct","getChallengers"));
			RequestPoster rp = new RequestPoster(domain, nameValuePairs);
			// array of ids
			String data = rp.getChallengers();
			
			json = new JSONObject(data);
			
			// Make array of names
			JSONArray names = json.getJSONArray("data");
			for(int i = 0; i < names.length(); i++){
				JSONObject single = names.getJSONObject(i);
				challengers.put(single.getString("uid"), single.getString("questions"));
			}
		}
		catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }

}
